package com.itheima.springbootfastjson2.config;

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

@Configuration
public class FastJson2Configuration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setReaderFeatures(
                // 优先考虑使用Java对象的字段（fields），而不是get方法
                JSONReader.Feature.FieldBased,
                // 在反序列化过程中将支持将JSON数组直接转换为JavaBean对象
                JSONReader.Feature.SupportArrayToBean
        );
        config.setWriterFeatures(
                // 优先考虑使用Java对象的字段（fields），而不是set方法
                JSONWriter.Feature.FieldBased,
                // 会序列化值为空的字段
                JSONWriter.Feature.WriteMapNullValue,
                // 允许在序列化JSON数据时添加额外的空格和换行符，使得生成的JSON字符串更易于阅读和调试
                JSONWriter.Feature.PrettyFormat
        );
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(0, converter);

//        WebMvcConfigurer.super.configureMessageConverters(converters);
    }
}
